-module(rtps_dr).

%%% @doc This is what a data reader should look like more or less.

-behaviour(gen_server).

%% -include_lib("kernel/include/logger.hrl").
-include("rtps.hrl").
-include("rtps_history_cache.hrl").

%% API
-export([start_link/2, read/1, take/1]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).

-record(data, {r :: pid(), rhc :: pid()}).

%%%===================================================================
%%% API
%%%===================================================================

start_link(R, RHC) ->
    gen_server:start_link(?MODULE, [R, RHC], []).

-spec read(Pid) -> [Change] when
      Pid :: pid(),
      Change :: rtps_history_cache:cache_change().
read(Pid) ->
    gen_server:call(Pid, read).

-spec take(Pid) -> [Change] when
      Pid :: pid(),
      Change :: rtps_history_cache:cache_change().
take(Pid) ->
    gen_server:call(Pid, take).

%%%===================================================================
%%% gen_server callbacks
%%%===================================================================

%% @private
init([R, RHC]) ->
    {ok, #data{r = R, rhc = RHC}}.

%% @private
handle_call(read, _From, #data{rhc = RHC} = Data) ->
    Reply = rtps_history_cache:available_changes(RHC),
    %% TODO: In the specs, 8.2.9.2.2 and 8.2.9.2.3, something with the DDS
    %% filter is also done.
    {reply, Reply, Data};
handle_call(take, _From, #data{rhc = RHC} = Data) ->
    Changes = rtps_history_cache:available_changes(RHC),
    %% TODO: In the specs, 8.2.9.2.2 and 8.2.9.2.3, something with the DDS
    %% filter is also done.
    [rtps_history_cache:remove_change(RHC, Change) || Change <- Changes],
    Reply = Changes,
    {reply, Reply, Data};
handle_call(_Request, _From, Data) ->
    Reply = ok,
    {reply, Reply, Data}.

%% @private
handle_cast(_Msg, Data) ->
    {noreply, Data}.

%% @private
handle_info(_Info, Data) ->
    {noreply, Data}.

%% @private
terminate(_Reason, _Data) ->
    ok.

%% @private
code_change(_OldVsn, Data, _Extra) ->
    {ok, Data}.

%%%===================================================================
%%% Internal functions
%%%===================================================================
